//
//  MineAddressAddViewController.m
//  MJApp
//
//  Created by wangliang on 15/3/29.
//  Copyright (c) 2015年 wangliang. All rights reserved.
//

#import "MineAddressAddViewController.h"
#import "MineAddressAddInfoTableViewCell.h"
#import "MineInfoEditEndTableViewCell.h"
#import "MineAddressDefaultTableViewCell.h"
#import "NSString+Extension.h"

@interface MineAddressAddViewController ()<UITableViewDelegate,UITableViewDataSource,HomeCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *addAddressTableView;
@property (nonatomic, strong) NSArray *tableArray;
@property (nonatomic, strong) NSMutableDictionary *tableDic;
@property (nonatomic, strong) NSDictionary *infoDic;
@property (nonatomic, strong) MineAddressDefaultTableViewCell *defaultCell;
@property (nonatomic,strong) NSArray *addrList;
@property (nonatomic, assign) BOOL isDefault;

@end

@implementation MineAddressAddViewController

- (instancetype)initWithDic:(NSDictionary *)infoDic {
    
    if (self = [super init]) {
    
        self.infoDic = infoDic;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self obationAddrList];
    [self Data];
    [self UI];
    [self NaviUI];
}

- (void)Data {
    
    self.isDefault = YES;
    self.tableArray = @[@"收货人姓名",@"手机号码",@"邮政编码",@"省、市、区",@"详情地址"];
    if (self.infoDic) {
        
        NSString *area = [NSString stringWithFormat:@"%@ %@ %@",self.infoDic[@"economize"],self.infoDic[@"city"],self.infoDic[@"area"]];
        self.title = @"修改收货地址";
        self.isDefault = ([self.infoDic[@"defaultAddress"] integerValue] == 1);
        self.tableDic = [@{
                           self.tableArray[0]:self.infoDic[@"name"],
                           self.tableArray[1]:self.infoDic[@"phone"],
                           self.tableArray[2]:self.infoDic[@"post_code"],
                           self.tableArray[3]:area,
                           self.tableArray[4]:self.infoDic[@"address"],
                           } mutableCopy];
    }else {
        
        self.title = @"新增收货地址";
        self.tableDic = [@{
                           self.tableArray[0]:@"",
                           self.tableArray[1]:@"",
                           self.tableArray[2]:@"",
                           self.tableArray[3]:@"",
                           self.tableArray[4]:@"",
                           } mutableCopy];
    }
    
}
- (void)obationAddrList {
    
    [WLHttpRequestAfter addressListWithParam:nil usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        
        if ([resultDictionary[@"status"] integerValue] == 1) {
            
            NSData *jsonData = [resultDictionary[@"data"] dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *arrayList = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            self.addrList = arrayList;
            [self.addAddressTableView reloadData];
        }
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}

- (void)UI {
    
    
    self.addAddressTableView.delegate = self;
    self.addAddressTableView.dataSource = self;
    self.addAddressTableView.backgroundColor = Color_Back_Black;
    self.addAddressTableView.separatorColor = [UIColor clearColor];
    self.addAddressTableView.contentInset = UIEdgeInsetsMake(0, 0, -44, 0);
}

- (void)NaviUI {
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn] ;
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)btnAction:(UIButton *)sender {
    
    
    [self.view endEditing:YES];
    
    NSString *nameStr = [self.tableDic[self.tableArray[0]] stringWithNoEmpty];
    NSString *phoneStr = [self.tableDic[self.tableArray[1]] stringWithNoEmpty];
    NSString *codeStr = [self.tableDic[self.tableArray[2]] stringWithNoEmpty];
    NSString *addrStr = [self.tableDic[self.tableArray[3]] stringWithNoEmpty];
//    NSString *addrStreetStr = [self.tableDic[self.tableArray[4]] stringWithNoEmpty];
    NSString *addrInfoStr = [self.tableDic[self.tableArray[4]] stringWithNoEmpty];
    
    BOOL nameBool = [nameStr isEqual:@""];
    BOOL phoneBool = [phoneStr isEqual:@""] ||![BCBaseObject isMobileNumber:phoneStr];
    BOOL postcodeBool = [codeStr isEqual:@""];
    BOOL addrBool = [addrStr isEqual:@""];
//    BOOL addrStreetBool = [addrStreetStr isEqual:@""];
    BOOL addrInfoBool = [addrInfoStr isEqual:@""];
    if (nameBool) {
        
        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"收货人姓名不能为空"];
    }else if(phoneBool) {
        
        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"请填写正确的手机号"];
    }else if(addrBool) {
        
        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"省市区不能为空"];
    }else if(addrInfoBool) {
        
        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"详情地址不能为空"];
    }else {
        
        NSDictionary *dic = @{
        @"name":nameStr,
        @"phone":phoneStr,
        @"code":codeStr,
        @"addr":addrStr,
//        @"addrStreet":addrStreetStr,
        @"addrInfoStr":addrInfoStr
        };
        [self postData:dic];
    }
}

- (void)postData:(NSDictionary *)dic {
    
    NSString *addressId = @"0";
    if (self.infoDic) {
        
        addressId = self.infoDic[@"id"];
    }
    NSArray *addressArray = [dic[@"addr"] componentsSeparatedByString:@" "];
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    dic1[@"user_id"] = [userInfoTool share].ID;
    dic1[@"address_id"] = addressId;
    dic1[@"name"] = dic[@"name"];
    dic1[@"economize"] = addressArray[0];
    dic1[@"city"] = addressArray[1];
    dic1[@"area"] = addressArray[2];
    dic1[@"address"] = dic[@"addrInfoStr"];
    dic1[@"post_code"] = dic[@"code"];
    dic1[@"defaultAddress"] = @(self.isDefault);
    dic1[@"phone"] = dic[@"phone"];
    dic1[@"email"] = @"";
    
    
    
    
    [WLHttpRequestAfter userEditAddressWithParam:dic1 usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        if ([resultDictionary[@"status"] integerValue] == 1) {
            
            [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"修改成功"];
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"addrChange" object:nil];
            if (self.infoDic) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addrInfo" object:nil userInfo:dic1];
            }
        }else {
            
            [[DMCAlertCenter defaultCenter] postAlertWithMessage:resultDictionary[@"msg"]];
        }
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.addrList) {
        
        return 2;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        
        return self.tableArray.count;
    }else {
        
        return 1;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == self.tableArray.count - 1) {
            
//            MineInfoEditEndTableViewCell *cell = (MineInfoEditEndTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
            return 139;
        }
    }
    MineAddressDefaultTableViewCell *cell = (MineAddressDefaultTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHigh;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == self.tableArray.count - 1) {
            
            MineInfoEditEndTableViewCell *cell = [MineInfoEditEndTableViewCell initWithTableView:tableView];
            cell.infoDic = @{
            @"desc":self.tableArray[indexPath.row],
            @"value":self.tableDic[self.tableArray[indexPath.row]],
            @"index":@(indexPath.row)
            };
            cell.delegate = self;
            return cell;
        }else {

            MineAddressAddInfoTableViewCell *cell = [MineAddressAddInfoTableViewCell initWithTableView:tableView];
            cell.delegate = self;
            if (indexPath.row == 3) {
                cell.infoDic = @{
                                 @"desc":self.tableArray[indexPath.row],
                                 @"value":self.tableDic[self.tableArray[indexPath.row]],
                                 @"index":@(indexPath.row),
                                 @"addrList":self.addrList
                                 };
            }else {
                cell.infoDic = @{
                                 @"desc":self.tableArray[indexPath.row],
                                 @"value":self.tableDic[self.tableArray[indexPath.row]],
                                 @"index":@(indexPath.row)
                                 };
            }
            return cell;
        }
    }
    
     MineAddressDefaultTableViewCell *cell = [MineAddressDefaultTableViewCell initWithTableView:tableView];
    cell.selectImageView.highlighted = !self.isDefault;
    self.defaultCell = cell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        
        
        self.isDefault = self.defaultCell.selectImageView.highlighted;
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:indexPath.section];
        [tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
    }else if (indexPath.section == 0) {
        
        if (indexPath.row == 3) {
            
            NSLog(@"sfsf");
        }
    }
}


- (void)homeCell:(id)cell withInfo:(id)info {
    
    NSInteger index = [info[@"index"] integerValue];
    self.tableDic[self.tableArray[index]] = info[@"newString"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
